package com.teamone.etl.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @Description 订单编号生成
 * @Author ZhaoPeiJie
 * @Date 2021/1/20 17:01
 * @Version 1.0
 */
public class OrderUtils {
    /** 充值订单编号使用 */
    private static final String RECHARGE_CODE = "1";
    /** 随即编码 */
    private static final int[] R = new int[]{7, 9, 6, 2, 8 , 1, 3, 0, 5, 4};
    /** 用户id和随机数总长度 */
    private static final int MAXLENGTH = 14;
    /** 固定长度随机码起始数 */
    private static final int MIN = 1;
    /** 固定长度随机码结尾数 */
    private static final int MAX = 9;
    /**
     * 更具id进行加密+加随机数组成固定长度编码
     */
    private static String toCode(Integer id) {
        String idStr = id.toString();
        StringBuilder idsbs = new StringBuilder();
        for (int i = idStr.length() - 1 ; i >= 0; i--) {
            idsbs.append(R[idStr.charAt(i)-'0']);
        }
        return idsbs.append(getRandom(MAXLENGTH - idStr.length())).toString();
    }

    /**
     * 生成时间戳
     */
    private static String getDateTime(){
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
    }

    /**
     * 生成固定长度随机码
     * @param n    长度
     */
    private static long getRandom(long n) {
        long min = MIN,max = MAX;
        for (int i = 1; i < n; i++) {
            min *= 10;
            max *= 10;
        }
        long rangeLong = (((long) (new Random().nextDouble() * (max - min)))) + min ;
        return rangeLong;
    }

    /**
     * 生成不带类别标头的编码
     * @param  accountId
     */
    private static synchronized String getCode(Integer accountId){
        accountId =  accountId == null ? 10000 :  accountId;
        return getDateTime() + toCode(accountId);
    }

    /**
     * 生成订单单号编码
     * @param  accountId
     */
    public static String getOrderCode(Integer accountId){
        return RECHARGE_CODE + getCode(accountId).substring(10,20);
    }
}
